﻿using System;
using System.Windows.Threading;

using VSTalk.Engine.Core.XmppConnection;
using VSTalk.Model;
using VSTalk.Tools;

using agsXMPP;
using agsXMPP.protocol.client;

namespace VSTalk.Engine.Core.Feed
{
    public class XmppClientMessageProvider : IMessageProvider, IListener
    {
        private readonly XmppClientConnection _connection;
        private readonly Client _client;
        private IActionWrapper<object, Message> _onMessage;

        public XmppClientMessageProvider(ClientConnection clientConnection)
        {
            _connection = clientConnection.Connection;
            _client = clientConnection.Client;
        }

        public void StartListen()
        {
            var dispatcher = Dispatcher.CurrentDispatcher;
            _onMessage = dispatcher.Wrap<object, Message>(ConnectionOnMessage);
            _connection.OnMessage += _onMessage.Exec;
        }

        public void StopListen()
        {
            _connection.OnMessage -= _onMessage.Exec;
        }

        private void ConnectionOnMessage(object sender, Message msg)
        {
            OnMessageReceived(new MessageReceivedArgs
            {
                Message = Create(msg)
            });
        }

        private IMessage Create(Message msg)
        {
            return new FeedMessage
            {
                XmppMessage = msg,
                Date = DateTime.Now,
                ClientId = _client.Id
            };
        }

        public event EventHandler<MessageReceivedArgs> MessageReceived;

        protected virtual void OnMessageReceived(MessageReceivedArgs e)
        {
            var handler = MessageReceived;
            if (handler != null) handler(this, e);
        }
    }
}